<?PHP
/**
 * @dbDonor.php
 * Controls database operations on the dbdonor table.
 *
 * Copyright 2011 by Matthew Wakim.  This program is part of Donate.
 * Donate is free software.  It comes with absolutely no warranty.
 * You can redistribute it and/or modify it under the terms of the GNU
 * General Public License as published by the Free Software Foundation
 * (see <http://www.gnu.org/licenses/ for more information).
 *
 * @version March 5th 2011
 * @author Matthew Wakim
 */


/**
 *includes the file donor.php once in this db control
 *@param
 *@return
 */
include_once('dbConnect.php');
include_once('../model/Donor.php');
Class dbDonor {

	/**
	 *this function sets up the database for donor.
	 *@param
	 *@return
	 */
	static function createTable() {

		$query =("CREATE  TABLE donor
(
  donorID INT         NOT NULL AUTO_INCREMENT ,
  street  VARCHAR(25) NULL ,
  city    VARCHAR(20) NULL ,
  stateName   VARCHAR(2)  NULL ,
  zip     VARCHAR(10) NULL ,
  phone   VARCHAR(14) NULL ,
  fax     VARCHAR(14) NULL ,
  email   VARCHAR(30) NULL ,
  CONSTRAINT pk_donor PRIMARY KEY (`donorID`) 
  );
  ");

		connect();
		$result = mysql_query($query);
		echo mysql_error();
		mysql_close();
		if ($result == false) {
			return false;
		}

		//Previous query was successful.
		return true;
	}
	/**
	 *this function gets the donorID field from its location
	 *@param
	 *@return
	 */
	function getdonorID($d) {
		connect();
		$result = mysql_query("SELECT donorID FROM donor WHERE donorID='$d'");
		$row = mysql_fetch_row($result);
		return $row[0];
	}
	/** this function gets the street field from its location
	 */
	function getstreet($d) {
		connect();
		$result = mysql_query("SELECT street FROM donor WHERE donorID='$d'");
		$row = mysql_fetch_row($result);
		return $row[0];
	}
	/** this function gets the city field from its location
	 */
	function getcity($d) {
		connect();
		$result = mysql_query("SELECT city FROM donor WHERE donorID='$d'");
		$row = mysql_fetch_row($result);
		return $row[0];
	}
	/** this function gets the state field from its location
	 */
	function getstate($d) {
		connect();
		$result = mysql_query("SELECT state FROM donor WHERE donorID='$d'");
		$row = mysql_fetch_row($result);
		return $row[0];
	}
	/** this function gets the zip field from its location
	 */
	function getzip($d) {
		connect();
		$result = mysql_query("SELECT zip FROM donor WHERE donorID='$d'");
		$row = mysql_fetch_row($result);
		return $row[0];
	}
	/** this function gets the phone field from its location
	 */
	function getphone($d) {
		connect();
		$result = mysql_query("SELECT phone FROM donor WHERE donorID='$d'");
		$row = mysql_fetch_row($result);
		return $row[0];
	}
	/**
	 *	 this function gets the fax field from its location
	 */
	function getfax($d) {
		connect();
		$result = mysql_query("SELECT fax FROM donor WHERE donorID='$d'");
		$row = mysql_fetch_row($result);
		return $row[0];
	}
	/**
	 * this function gets the email field from its location
	 */
	function getemail($d) {
		connect();
		$result = mysql_query("SELECT email FROM donor WHERE donorID='$d'");
		$row = mysql_fetch_row($result);
		return $row[0];
	}

	/**
	 *	 this function adds all the fields from the donor table into their fields in the database.
	 */
	static function addDonorByFieldsInArray($allFields, &$id)
	{
		extract($allFields);
		$d = new Donor($allFields);

		$result = dbDonor::addDonor($d, $id);
		if ($result == false) {
			echo ("Donor could not be updated with specified information.<br />");
			return false;
		}
		return true;
	}
	
	static function verifyInsertedDonor($id)
	{
		$output = "";
		$error = dbDonor::getAllByID($id, $output);
		if ($error == true) {
			printf("%s<br />", $output);
		}
		else {
			$ind = new Donor($output['street'], $output['city'], $output['stateName'], $output['zip'],$output['phone'],$output['fax'],$output['email']);
			printf("Inserted: Donor with ID=%d has %s.<br />", $id, $ind->printAllAttributes( ));
		}
	}

	static function addDonor($v, &$id) {
		if (!$v instanceof Donor) {
			echo ("Invalid arguement insertInto ( ) function<br />");
			return false;
		}
		//Compose the INSERT INTO query srting. Primary key value is missing.
		//Database server automatically generates a unique ID for the primary Key.
		$query = sprintf("INSERT INTO donor VALUES(null, '%s', '%s', '%s', '%s', '%s', '%s', '%s' )",
		$v->getStreet(),
		$v->getCity(),
		$v->getStateName(),
		$v->getZip(),
		$v->getPhone(),
		$v->getFax(),
		$v->getEmail()
		);
		connect( );
		$result = mysql_query($query);
		//printf("Donor added has id %d\n<br />", mysql_insert_id());
		$id = mysql_insert_id( );
		mysql_close( );
		if ($result == false) {
			echo mysql_error();
			return false;
		}
		//query was successful.
		return true;
	}


	/**
	 * this function deletes a donor from their location in the database
	 */
	static function deleteDonor($id) {
		connect();
		//$i = $d->getdonorID();
		$result = mysql_query("DELETE FROM donor WHERE donorID='$id'");
		mysql_close( );
	}

	public static function getAllByID($id, &$output) {
		$query = sprintf("SELECT street, city, stateName, zip, phone, fax, email FROM donor WHERE donorID=%d",
		$id);
		// printf("->Query: %s<br />", $query);

		connect( );
		$result = mysql_query($query);
		mysql_close( );

		if ($result == false) {
			$output = sprintf("%s", mysql_error());
			return false;
		}
		//process result and print out warning or attribute values
		return dbDonor::checkForOneInstance($result, $id, $output);
	}
	
	/**
	 * @author Matt V
	 * @param array $allIndArray
	 * Returns individuals given id
	 */
	static function getDonorById($id) {
		connect( );
		$result = mysql_query("SELECT donorID, street, city, stateName, zip, phone, fax, email
		FROM Donor WHERE donorID='$id'");
		mysql_close( );
		if ($result == false) {
			return false;
		}
		$numOfRows = mysql_num_rows($result);
		$allIndArray = array();
		for($i = 0; $i < $numOfRows; $i++){
			$currentRow = mysql_fetch_assoc($result);
			$allIndArray = $currentRow;
		}
		return $allIndArray;
	}

	
	private static function checkForOneInstance($result, $id, &$output)
	{
		//Local variables are initialized.
		//Think positively about what this checking returns :-) and set $errorStatus
		//to initial value false
		$errorStatus = false;

		$howMany = mysql_num_rows($result);
		// printf("-->Found %d instance(s) for donorID=%d.<br />", $howMany, $id);
		switch ($howMany) {
			case 0:
				$output = sprintf("No donor instance with ID=%d was found.",
				$id);
        $errorStatus = true;
        break;
      case 1:
        //mysql_fetch( ) DOES NOT return primary key values!
        $output = mysql_fetch_assoc($result);
        $errorStatus = false;
        break;
      default:
        $output = sprintf("There are multiple donor instances 
                           with ID=%d.", $id);
        $errorStatus = true;
        break;
    }
    return $errorStatus;
  }
}
